<template>
  <div class="post-manage">
    <div class="header">
      <h2>内容管理</h2>
      <el-button type="primary" @click="showAddDialog">新增内容</el-button>
    </div>

    <!-- 统计卡片 -->
    <el-row :gutter="20" class="stats-cards">
      <el-col :span="4" v-for="(item, index) in stats" :key="index">
        <el-card shadow="hover">
          <div class="stats-item">
            <div class="stats-title">{{item.title}}</div>
            <div class="stats-value">{{item.value}}</div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 内容列表 -->
    <el-table :data="postList" border style="width: 100%; margin-top: 20px;">
      <el-table-column prop="content" label="内容" show-overflow-tooltip />
      <el-table-column prop="likeCount" label="点赞数" width="100" />
      <el-table-column prop="commentCount" label="评论数" width="100" />
      <el-table-column prop="createTime" label="发布时间" width="180">
        <template slot-scope="scope">
          {{formatDateTime(scope.row.createTime)}}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200">
        <template slot-scope="scope">
          <el-button size="mini" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button size="mini" type="danger" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="pageNum"
      :page-sizes="[10, 20, 50]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next"
      :total="total"
      style="margin-top: 20px;">
    </el-pagination>

    <!-- 新增/编辑对话框 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible">
      <el-form :model="postForm" :rules="rules" ref="postForm">
        <el-form-item label="内容" prop="content">
          <el-input type="textarea" v-model="postForm.content" :rows="4"></el-input>
        </el-form-item>
        <el-form-item label="图片">
          <el-upload
            class="upload-demo"
            action="/api/posts/upload"
            :headers="uploadHeaders"
            :on-success="handleUploadSuccess"
            :on-error="handleUploadError"
            :before-upload="beforeUpload"
            :limit="1"
            accept=".jpg,.jpeg,.png,.gif"
          >
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传jpg/png/gif文件，且不超过5MB</div>
          </el-upload>
          <div class="preview-image" v-if="postForm.imageUrl">
            <el-image :src="postForm.imageUrl" style="width: 200px">
              <div slot="error">
                <i class="el-icon-picture-outline"></i>
              </div>
            </el-image>
            <i class="el-icon-delete" @click="removeImage"></i>
          </div>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitPost">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import router from "@/router";

export default {
  name: 'PostManage',
  data() {
    return {
      postList: [],
      pageNum: 1,
      pageSize: 10,
      total: 0,
      stats: [],
      dialogVisible: false,
      dialogTitle: '',
      postForm: {
        id: null,
        content: '',
        imageUrl: ''
      },
      rules: {
        content: [
          { required: true, message: '请输入内容', trigger: 'blur' }
        ]
      },
      uploadHeaders: {
        'satoken': localStorage.getItem('token')
      }
    }
  },
  created() {

      this.fetchData()
      this.fetchStats()
  },
  methods: {
    async fetchData() {
      try {
        const res = await this.$http.get('/api/posts/list', {
          params: {
            pageNum: this.pageNum,
            pageSize: this.pageSize
          }
        })
        this.postList = res.data.data.records
        this.total = res.data.data.total
      } catch (error) {
        this.$message.error('获取数据失败')
      }
    },

    async fetchStats() {
      try {
        const res = await this.$http.get('/api/posts/admin/stats')
        const data = res.data.data
        this.stats = [
          { title: '总内容数', value: data.totalPosts },
          { title: '总点赞数', value: data.totalLikes },
          { title: '总评论数', value: data.totalComments },
          { title: '今日内容', value: data.todayPosts },
          { title: '今日评论', value: data.todayComments }
        ]
      } catch (error) {
        this.$message.error('获取统计数据失败')
      }
    },

    showAddDialog() {
      this.dialogTitle = '新增内容'
      this.postForm = {
        id: null,
        content: '',
        imageUrl: ''
      }
      this.dialogVisible = true
    },

    handleEdit(row) {
      this.dialogTitle = '编辑内容'
      this.postForm = {
        id: row.id,
        content: row.content,
        imageUrl: row.imageUrl
      }
      this.dialogVisible = true
    },

    async handleDelete(row) {
      try {
        await this.$confirm('确认删除该内容吗？', '提示', {
          type: 'warning'
        })
        
        const res = await this.$http.delete(`/api/posts/admin/delete/${row.id}`)
        if (res.data.code === 200) {
          this.$message.success('删除成功')
          this.fetchData()
        }
      } catch (error) {
        if (error !== 'cancel') {
          this.$message.error('删除失败')
        }
      }
    },

    async submitPost() {
      try {
        await this.$refs.postForm.validate()
        
        let res
        if (this.postForm.id) {
          res = await this.$http.put('/api/posts/admin/update', this.postForm,
              {
                headers: {
                  'Content-Type': 'application/json' // 设置请求头
                }
              })
        } else {
          res = await this.$http.post('/api/posts/admin/add', this.postForm,
              {
                headers: {
                  'Content-Type': 'application/json' // 设置请求头
                }
              })
        }

        if (res.data.code === 200) {
          this.$message.success(this.postForm.id ? '更新成功' : '添加成功')
          this.dialogVisible = false
          this.fetchData()
        }
      } catch (error) {
        if (error !== false) {
          this.$message.error(this.postForm.id ? '更新失败' : '添加失败')
        }
      }
    },

    handleSizeChange(val) {
      this.pageSize = val
      this.fetchData()
    },

    handleCurrentChange(val) {
      this.pageNum = val
      this.fetchData()
    },

    formatDateTime(time) {
      if (!time) return ''
      const date = new Date(time)
      return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`
    },

    handleUploadSuccess(res) {
      if (res.code === 200) {
        this.postForm.imageUrl = res.data
        this.$message.success('图片上传成功')
      } else {
        this.$message.error(res.msg || '上传失败')
      }
    },

    handleUploadError() {
      this.$message.error('上传失败')
    },

    beforeUpload(file) {
      const isImage = /^image\/(jpeg|png|gif)$/.test(file.type)
      const isLt5M = file.size / 1024 / 1024 < 5

      if (!isImage) {
        this.$message.error('上传图片只能是 JPG/PNG/GIF 格式!')
      }
      if (!isLt5M) {
        this.$message.error('上传图片大小不能超过 5MB!')
      }
      return isImage && isLt5M
    },

    removeImage() {
      this.postForm.imageUrl = ''
    }
  }
}
</script>

<style scoped>
.post-manage {
  padding: 20px;
}
.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}
.stats-cards {
  margin-bottom: 20px;
}
.stats-item {
  text-align: center;
}
.stats-title {
  font-size: 14px;
  color: #666;
}
.stats-value {
  font-size: 24px;
  font-weight: bold;
  color: #409EFF;
  margin-top: 10px;
}
.preview-image {
  position: relative;
  display: inline-block;
  margin-top: 10px;
}

.preview-image .el-icon-delete {
  position: absolute;
  top: 0;
  right: 0;
  padding: 5px;
  color: #fff;
  background-color: rgba(0,0,0,0.6);
  border-radius: 0 0 0 4px;
  cursor: pointer;
}

.preview-image .el-icon-delete:hover {
  background-color: rgba(0,0,0,0.8);
}
</style>